package com.xk._01基础篇._05队列Queue.circle;

import java.util.Arrays;

/**
 * @description: 循环双端队列
 * @author: xu
 * @date: 2022/9/18 23:52
 */
@SuppressWarnings("unchecked")
public class CircleDeque<E> {
    private int size;
    private E[] elements;

    private int front; //头元素索引

    private static final int DEFAULT_CAPACITY = 10;

    public CircleDeque(){
        elements = (E[]) new Object[DEFAULT_CAPACITY];
    }

    /**
     * 元素的数量
     */
    public int size() {
        return size;
    }

    /**
     * 判空
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 清空
     */
    public void clear() {
        for (int i = 0; i < size; i++) {
            elements[index(i)] = null;
        }
        size = 0;
        front = 0;
    }

    /**
     * 尾部入队 尾部添加元素
     */
    public void enQueueRear(E element) {
        ensureCapacity(size + 1);
        elements[index(size)] = element;
        size++;
    }

    /**
     * 头部出队 头部删除元素
     */
    public E deQueueFront() {
        E frontElement = elements[front];
        elements[front] = null;
        front = index(1);
        size--;
        return frontElement;
    }

    /**
     * 头部入队 头部添加元素
     */
    public void enQueueFront(E element) {
        ensureCapacity(size + 1);
        front = index(elements.length - 1);
        elements[front] = element;
        size++;
    }

    /**
     * 尾部出队 尾部删除元素
     */
    public E deQueueRear() {
        int rearIndex = index(size - 1);
        E rear = elements[rearIndex];
        elements[rearIndex] = null;
        size--;
        return rear;
    }

    /**
     * 获取队头元素
     */
    public E front() {
        return elements[front];
    }

    /**
     * 获取队尾元素
     */
    public E rear() {
        return elements[index(size - 1)];
    }

    /**
     * 索引映射封装
     */
    private int index(int index){
        index += front;
        return index - (index >= elements.length ? elements.length : 0);
        //return (index + front) % elements.length;
    }

    private void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity) return;
        //新容量为旧容量的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElements = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newElements[i] = elements[index(i)];
        }
        elements = newElements;
        front = 0;
    }

    @Override
    public String toString() {
        return "CircleQueue{" +
                "size=" + size +
                ", elements=" + Arrays.toString(elements) +
                ", front=" + front + ", capacity=" + elements.length +
                '}';
    }
}
